﻿using System.Collections.Generic;
using DtoModels;
using Entities;
using Microsoft.AspNetCore.Mvc;
using Portal.Filter;
using Portal.Models;
using SqlSugar;

namespace Portal.Controllers
{
    /// <summary>
    /// 部门管理业务
    /// </summary>
    [LoginCheckFilter(IsCheck = true)]
    public class DeptController : Controller
    {
        private readonly SqlSugarClient _sqlSugarClient;

        public DeptController(SqlSugarClient sqlSugarClient)
        {
            _sqlSugarClient = sqlSugarClient;
        }

        /// <summary>
        /// 查询所有部门
        /// </summary>
        /// <param name="deptInfoReqDto"></param>
        /// <returns></returns>
        public ActionResult LoadAllDept(DeptInfoReqDto deptInfoReqDto)
        {
            var totalCount = 0;
            var querySqlQueryable = this._sqlSugarClient.Context.Queryable<sys_dept>();

            if (deptInfoReqDto.Id!=0)
            {
                querySqlQueryable = querySqlQueryable.Where(x => x.id == deptInfoReqDto.Id || x.pid == deptInfoReqDto.Id);
            }

            if (!string.IsNullOrEmpty(deptInfoReqDto.Title))
            {
                querySqlQueryable = querySqlQueryable.Where(x => x.title.Contains(deptInfoReqDto.Title));
            }

            if (!string.IsNullOrEmpty(deptInfoReqDto.Address))
            {
                querySqlQueryable = querySqlQueryable.Where(x => x.address.Contains(deptInfoReqDto.Address));
            }

            if (!string.IsNullOrEmpty(deptInfoReqDto.Remark))
            {
                querySqlQueryable.Where(x => x.remark.Contains(deptInfoReqDto.Remark));
            }

            var queryResult = querySqlQueryable.ToPageList(deptInfoReqDto.Page, deptInfoReqDto.Limit, ref totalCount);

            var result = new DeptInfoResDto
            {
                Code = 0,
                Msg = "查询成功",
                Count = totalCount,
                Data = queryResult
            };

            return Json(result);
        }

        /// <summary>
        /// 查询部门DTree树
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadDeptManagerLeftTreeJson()
        {

            var querySqlQueryable = this._sqlSugarClient.Queryable<sys_dept>().ToList();

            var list = new List<DTreeResDto>();

            foreach (var item in querySqlQueryable)
            {
                list.Add(new DTreeResDto
                {
                    Id = item.id,
                    CheckArr = item.open.ToString(),
                    Title = item.title,
                    ParentId = item.pid
                });
            }

            var result = new LayUiStandardResDto<DTreeResDto>
            {
                Code = 0,
                Msg = "查询成功",
                Data = list
            };

            return Json(result);

            /*
             * 返回的json格式示例:
             *
             * {
             *   "code":0,
             *   "msg":"操作成功",
             *   "data": [{"id":"001","title": "湖南省","checkArr": "0","parentId": "0"},
             *   {"id":"002","title": "湖北省","checkArr": "0","parentId": "0"},
             *   {"id":"003","title": "广东省","checkArr": "0","parentId": "0"},
             *   {"id":"004","title": "浙江省","checkArr": "0","parentId": "0"},
             *   {"id":"005","title": "福建省","checkArr": "0","parentId": "0"},
             *   {"id":"001001","title": "长沙市","checkArr": "0","parentId": "001"},
             *   {"id":"001002","title": "株洲市","checkArr": "0","parentId": "001"},
             *   {"id":"001003","title": "湘潭市","checkArr": "0","parentId": "001"},
             *   {"id":"001004","title": "衡阳市","checkArr": "0","parentId": "001"},
             *   {"id":"001005","title": "郴州市","checkArr": "0","parentId": "001"}]
             * }
             */
        }

        /// <summary>
        /// 获取部门当前最大的排序码
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadDeptMaxOrderNum()
        {
            var maxOrderNum = this._sqlSugarClient.Queryable<sys_dept>().Max(x => x.ordernum);

            return Json(new {value = (maxOrderNum + 1)});
        }

        /// <summary>
        /// 添加部门
        /// </summary>
        /// <returns></returns>
        public ActionResult AddDept(sys_dept addDept)
        {
           var insertNum = this._sqlSugarClient.Insertable<sys_dept>(addDept).ExecuteCommand();

           var result = new LayUiStandardResDto<object>
           {
               Code = GlobalVariable.Ok,
               Msg = $"成功添加{insertNum}个部门"
           };

           return Json(result);
        }

        /// <summary>
        /// 检查当前部门是否存在子部门,如果存在则不允许删除
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckDeptHasChildrenNode(int id)
        {
            var count = this._sqlSugarClient.Queryable<sys_dept>().Count(x => x.pid == id);
            
            if (count>0)  //存在子部门
            {
                return Json(new {value = true});
            }

            return Json(new { value = false });
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DeleteDept(int id)
        {
            var deleteNum = this._sqlSugarClient.Deleteable<sys_dept>(x => x.id == id).ExecuteCommand();
            var result = new LayUiStandardResDto<object>
            {
                Code = GlobalVariable.Ok,
                Msg = $"成功删除了{deleteNum}个部门"
            };

            return Json(result);
        }

        /// <summary>
        /// 更新部门信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult UpdateDept(sys_dept dept)
        {
            var updateNum = this._sqlSugarClient.Updateable<sys_dept>(dept).ExecuteCommand();
            var result = new LayUiStandardResDto<object>
            {
                Code = GlobalVariable.Ok,
                Msg = $"成功更新了{updateNum}个部门信息"
            };

            return Json(result);
        }
    }
}